import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mall/constant/app_colors.dart';
import 'package:mall/constant/app_dimens.dart';
import 'package:mall/constant/app_strings.dart';
import 'package:mall/constant/text_style.dart';
import 'package:mall/modules/model/category_entity.dart';
import 'package:mall/modules/sc/category_sc.dart';
import 'package:mall/ui/widgets/empty_data.dart';
import 'package:mall/utils/list_placeholder_component/list_placeholder_component.dart';
import 'package:mall/router/navigator_util.dart';
import 'package:mall/utils/refresh/refresh_widget.dart';
import 'package:mall/utils/refresh/warp_refresh_controller.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class TabCategoryPage extends StatefulWidget {
  @override
  _TabCategoryPageState createState() => _TabCategoryPageState();
}

class _TabCategoryPageState extends State<TabCategoryPage> {
  // TabCategoryViewModel _tabCategoryViewModel = TabCategoryViewModel();
  // RefreshController _refreshController = RefreshController();

  final sc_category = Get.put(CategoryListSc());
  final sc_subCategory = Get.put(SubCategoryListSc());
  late final _refreshController = WarpRefreshController(loadState: sc_category.loadState);

  RxInt _currentIndex = 0.obs;

  @override
  void initState() {
    super.initState();
    // _tabCategoryViewModel.onRefresh();
    sc_category.refreshData().then((value) {
      //找到第一个
      if (sc_category.data.isNotEmpty) {
        final first = sc_category.data.first;
        sc_subCategory.categoryId = first.id;
        sc_subCategory.refreshData();
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    _refreshController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(AppStrings.CATEGORY),
          centerTitle: true,
          actions: <Widget>[
            IconButton(
              icon: Icon(
                Icons.search,
                color: AppColors.C_FFFFFF,
              ),
              onPressed: () {},
            )
          ],
        ),
        // body: RefreshConfiguration(
        //   child: SmartRefresher(
        //       enablePullUp: false,
        //       header: WaterDropMaterialHeader(
        //         backgroundColor: AppColors.COLOR_FF5722,
        //       ),
        //       controller: _refreshController,
        //       onRefresh: () => _tabCategoryViewModel.onRefresh(),
        //       child: Container(
        //           child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
        //         new Expanded(
        //           flex: 2,
        //           child: _parentCategoryWidget(_tabCategoryViewModel),
        //         ),
        //         new Expanded(
        //           flex: 8,
        //           child: _tabCategoryViewModel.childCategories.length == 0
        //               ? EmptyDataView()
        //               : _childCategoryWidget(_tabCategoryViewModel),
        //         ),
        //       ]))),
        // ),
        body: Obx(
          () => RefreshComponent(
            controller: _refreshController,
            onRefresh: () => sc_category.refreshData(),
            child: WrappedListPlaceholderComponent.widget(
              sc: sc_category,
              // child: _childCategoryWidget(sc_category.data),
              builder: (p0) => Container(
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    new Expanded(
                      flex: 2,
                      child: _parentCategoryWidget(p0),
                    ),
                    new Expanded(
                      flex: 8,
                      child: sc_subCategory.data.length == 0
                          ? EmptyDataView()
                          : _childCategoryWidget(p0, sc_subCategory.data),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ));
  }

  Widget _parentCategoryWidget(List<CategoryEntity> parentCategories) {
    // return Selector<TabCategoryViewModel, TabCategoryViewModel>(
    //   shouldRebuild: (previous, next) => previous.parentShouldBuild,
    //   selector: (context, provider) => provider,
    //   builder: (context, provider, child) {
    //     provider.parentRebuild();
    //     return ListView.builder(
    //         physics: NeverScrollableScrollPhysics(),
    //         padding: EdgeInsets.all(0),
    //         itemCount: provider.parentCategories.length,
    //         itemBuilder: (BuildContext context, int index) {
    //           return Selector<TabCategoryViewModel, int>(
    //             selector: (context, provider) {
    //               return provider.selectIndex;
    //             },
    //             builder: (context, data, child) {
    //               return _getFirstLevelView(provider.parentCategories[index], index, data);
    //             },
    //           );
    //         });
    //   },
    // );
    return Obx(() => ListView.builder(
        physics: NeverScrollableScrollPhysics(),
        padding: EdgeInsets.all(0),
        itemCount: parentCategories.length,
        itemBuilder: (BuildContext context, int index) {
          // return Selector<TabCategoryViewModel, int>(
          //   selector: (context, provider) {
          //     return provider.selectIndex;
          //   },
          //   builder: (context, data, child) {
          //     return _getFirstLevelView(provider.parentCategories[index], index, data);
          //   },
          // );
          return _getFirstLevelView(parentCategories[index], index, _currentIndex.value);
        }));
  }

  _itemParentClick(int index) {
    // _tabCategoryViewModel.setParentCategorySelect(index);
    _currentIndex.value = index;

    final parentCategory = sc_category.data[index];
    sc_subCategory.categoryId = parentCategory.id;
    sc_subCategory.refreshData();
  }

  Widget _getFirstLevelView(CategoryEntity categoryEntity, int index, int selectIndex) {
    return InkWell(
      onTap: () => _itemParentClick(index),
      child: Container(
          color: AppColors.C_FFFFFF,
          width: 75,
          height: 45,
          alignment: Alignment.center,
          child: Row(
            children: <Widget>[
              Offstage(
                offstage: selectIndex != index,
                child: Container(
                  margin: EdgeInsets.only(top: 15, bottom: 15),
                  color: AppColors.C_FF5722,
                  width: ScreenUtil().setWidth(AppDimens.DIMENS_3),
                ),
              ),
              Container(
                margin: EdgeInsets.only(left: 15),
                height: 27.5,
                alignment: Alignment.center,
                child: Text(
                  categoryEntity.name ?? "",
                  style: selectIndex == index ? FMTextStyle.color_ff5722_size_13 : FMTextStyle.color_222222_size_13,
                ),
              )
            ],
          )),
    );
  }

  Widget _childCategoryWidget(List<CategoryEntity> parentCategories, List<CategoryEntity> subCategories) {
    // return Selector<TabCategoryViewModel, List<CategoryEntity>>(
    //     builder: (BuildContext context, List<CategoryEntity> data, Widget? child) {
    //   final list_category = sc_category.data;

    //   return SingleChildScrollView(
    //     physics: NeverScrollableScrollPhysics(),
    //     child: Column(
    //       children: [
    //         Container(
    //           height: ScreenUtil().setHeight(AppDimens.DIMENS_300),
    //           child: Image.network(
    //             _tabCategoryViewModel.categoryPicture ?? AppStrings.DEFAULT_URL,
    //             fit: BoxFit.fill,
    //           ),
    //         ),
    //         Padding(
    //           padding: EdgeInsets.only(top: ScreenUtil().setHeight(AppDimens.DIMENS_10)),
    //         ),
    //         Center(
    //           child: Text(
    //             _tabCategoryViewModel.categoryName ?? "",
    //             style: FMTextStyle.color_333333_size_42,
    //           ),
    //         ),
    //         GridView.builder(
    //             padding: EdgeInsets.all(0),
    //             physics: NeverScrollableScrollPhysics(),
    //             itemCount: _tabCategoryViewModel.childCategories.length,
    //             shrinkWrap: true,
    //             gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
    //                 crossAxisCount: 3,
    //                 mainAxisSpacing: 1,
    //                 childAspectRatio: 1.0,
    //                 //垂直单个子Widget之间间距
    //                 crossAxisSpacing: ScreenUtil().setHeight(AppDimens.DIMENS_10)),
    //             itemBuilder: (BuildContext context, int index) {
    //               return _getChildItemView(_tabCategoryViewModel.childCategories[index]);
    //             }),
    //         Padding(
    //           padding: EdgeInsets.only(top: 15),
    //         ),
    //       ],
    //     ),
    //   );
    // }, selector: (BuildContext context, TabCategoryViewModel tabCategoryViewModel) {
    //   return tabCategoryViewModel.childCategories;
    // });
    //当前选中的分类
    final selectCategory = parentCategories[_currentIndex.value];

    return SingleChildScrollView(
      physics: NeverScrollableScrollPhysics(),
      child: Column(
        children: [
          Container(
            height: ScreenUtil().setHeight(AppDimens.DIMENS_300),
            child: Image.network(
              selectCategory.picUrl ?? AppStrings.DEFAULT_URL,
              fit: BoxFit.fill,
            ),
          ),
          Padding(
            padding: EdgeInsets.only(top: ScreenUtil().setHeight(AppDimens.DIMENS_10)),
          ),
          Center(
            child: Text(
              selectCategory.name ?? "",
              style: FMTextStyle.color_222222_size_13,
            ),
          ),
          GridView.builder(
              padding: EdgeInsets.all(0),
              physics: NeverScrollableScrollPhysics(),
              itemCount: subCategories.length,
              shrinkWrap: true,
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 3,
                  mainAxisSpacing: 1,
                  childAspectRatio: 1.0,
                  //垂直单个子Widget之间间距
                  crossAxisSpacing: ScreenUtil().setHeight(AppDimens.DIMENS_10)),
              itemBuilder: (BuildContext context, int index) {
                return _getChildItemView(subCategories[index]);
              }),
          Padding(
            padding: EdgeInsets.only(top: 15),
          ),
        ],
      ),
    );
  }

  _itemChildClick(int? categoryId, String? categoryName) {
    NavigatorUtil.goCategoryGoodsListPage(context, categoryName, categoryId);
  }

  Widget _getChildItemView(CategoryEntity categoryEntity) {
    return GestureDetector(
      child: Card(
          child: Container(
        alignment: Alignment.center,
        width: ScreenUtil().setWidth(AppDimens.DIMENS_300),
        height: ScreenUtil().setHeight(AppDimens.DIMENS_300),
        child: Column(
          children: <Widget>[
            Image.network(
              categoryEntity.picUrl ?? "",
              fit: BoxFit.fill,
              width: ScreenUtil().setWidth(AppDimens.DIMENS_160),
              height: ScreenUtil().setWidth(AppDimens.DIMENS_160),
            ),
            Padding(
              padding: EdgeInsets.only(top: ScreenUtil().setHeight(AppDimens.DIMENS_10)),
            ),
            Text(
              categoryEntity.name ?? "",
              style: FMTextStyle.color_222222_size_13,
            ),
          ],
        ),
      )),
      onTap: () => _itemChildClick(categoryEntity.id, categoryEntity.name),
    );
  }
}
